package org.linloong.modules.apis.ai.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.linloong.core.result.Result;
import org.linloong.core.result.ResultEnum;
import org.linloong.modules.apis.ai.dto.ConversationVo;
import org.linloong.modules.apis.ai.entity.ChatHistory;
import org.linloong.modules.apis.ai.entity.CurrentChatHistory;
import org.linloong.modules.apis.ai.mapper.ChatHistoryMapper;
import org.linloong.modules.apis.ai.mapper.CurrentChatHistoryMapper;
import org.linloong.modules.apis.ai.service.CurrentChatHistoryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author dbo
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CurrentChatHistoryServiceImpl extends ServiceImpl<CurrentChatHistoryMapper, CurrentChatHistory> implements CurrentChatHistoryService {

    private final ChatHistoryMapper chatHistoryMapper;

    @Override
    public Result save(ConversationVo conversationVo) {
        if(StringUtils.isEmpty(conversationVo.getContent())){
            return Result.fail(ResultEnum.FAIL.getCode(), "发送消息不能为空！");
        }
        String userId = null;
        if(StringUtils.isEmpty(conversationVo.getUserId())){
            userId = StpUtil.getLoginId().toString();
        } else {
            userId = conversationVo.getUserId();
        }
        // 判断sessionID 是否存在
        // 存在的话，只存round history中
        String sessionId = IdUtil.simpleUUID();
        CurrentChatHistory history = CurrentChatHistory.builder()
                .userId(userId)
                .sessionId(sessionId)
                .content(conversationVo.getContent())
                .sender(conversationVo.getSender())
                .timestamp(Long.parseLong(conversationVo.getTimestamp()))
                .build();
        if(StringUtils.isEmpty(conversationVo.getSessionId())){

            chatHistoryMapper.insert(BeanUtil.copyProperties(history, ChatHistory.class));
            this.save(history);
            return Result.success(sessionId);
        } else {
            history.setSessionId(conversationVo.getSessionId());
            this.save(history);
            return Result.success();
        }
    }

    @Override
    public Map<String, Object> initChat(String sessionId) {
        List<CurrentChatHistory> list = this.list(Wrappers.<CurrentChatHistory>lambdaQuery()
                .eq(CurrentChatHistory::getSessionId, sessionId)
                .orderByAsc(CurrentChatHistory::getTimestamp)
        );
        return Map.of("list", list, "sessionId", sessionId);
    }
}
